package com.bb.blog.security.filter;

import com.alibaba.druid.util.StringUtils;
import jdk.nashorn.internal.parser.TokenType;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.token.TokenService;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RequiredArgsConstructor
public class    TokenFilter extends OncePerRequestFilter {
    public static String TOKEN_TYPE = "bearer";
    private final TokenStore tokenStore;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        if (!StringUtils.isEmpty(token)) {
            if(token.toLowerCase().startsWith(TOKEN_TYPE)){
                logger.info("认证token ---------> " + token);
                token = token.substring(TOKEN_TYPE.length() + 1);
                try {
                    Authentication authentication = tokenStore.readAuthentication(token);
                    SecurityContextHolder.getContext().setAuthentication(authentication);

                } catch (InvalidTokenException e) {
                    logger.info("token 验证失败 ：" + token);
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
